package org.example;

import io.cloudsoft.winrm4j.client.WinRmClientContext;
import io.cloudsoft.winrm4j.winrm.WinRmTool;
import io.cloudsoft.winrm4j.winrm.WinRmToolResponse;
import org.apache.cxf.common.util.StringUtils;
import org.apache.http.client.config.AuthSchemes;

import java.util.Optional;

/**
 * @author jiangjian
 * @desc 使用WinRM连接Windows
 * @since 2023/6/30 10:49
 */
public class WinRmConn {

    public static void windows() throws Exception {
        WinRmClientContext context = WinRmClientContext.newInstance();
        try {
            WinRmTool tool = WinRmTool.Builder.builder("192.168.2.204", "test", "test")
                    .authenticationScheme(AuthSchemes.NTLM)
                    .port(5985)
                    .useHttps(false)
                    .context(context)
                    .build();
            tool.setConnectionTimeout(3000L);
            tool.setOperationTimeout(6000L);

            WinRmToolResponse resp = tool.executeCommand("hostname");
            if (resp.getStatusCode() == 0) {
                String result = resp.getStdOut();
                if (!StringUtils.isEmpty(result)) {
                    // 去掉首尾空格 除空格以外的其他空白字符
                    result = result.trim().replaceAll(" [\\f\\n\\r\\t\\v]", "");
                    System.out.println(result);
                } else {
                    System.out.println("获取结果为空");
                }
            } else {
                System.out.println("Execute windows command fail: " + resp.getStdErr());
                throw new Exception(resp.getStdErr());
            }
        } catch (Exception e) {
            String msg = Optional.ofNullable(e.getMessage()).orElse("");
            if (msg.contains("timeout")) {
                throw new Exception("get session data time out");
            }
            throw e;
        } finally {
            context.shutdown();
        }
    }

}
